/**
 * 聚合图
 */
import echarts from 'echarts'; // echarts 文件引入
import sgisMapBase from "@/utils/map/sfgis.map.base.js";
import sgisLayerBase from '../../sfgis.layer.base';
// import sgisRegionBase from "../../sfgis.region.base.js";
import mapTool from "@/utils/map/sfgis.map.tool.js";
// import Layer from "@/utils/map/lib/main.js";
// import colorPicker from '../macrolayers/echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from '../macrolayers/echarts.stylemodify.js';
import mapexhance from "@/utils/map/lib/common/mapexhance.js";

export default {
  layerNum: 0, // 聚合图多能叠加10个，过多时提示移除，防止太卡
  colorNum:0,
  // colors: [
  //   "#EE7600",
  //   "#A65628",
  //   "#4DAF4A",
  //   "#1F78B4",
  //   "#FB8072",
  //   "#00CDCD",
  //   "#00868B",
  //   "#CD5555",
  //   "#FF0000",
  //   "#88E3CD",
  // ], // 聚合图配色方案
  //重置数据个数
  resetlayerNum(){
    this.layerNum=0;
  },
  //初始化图层信息
  initLayer(map,data){
    let clusterLayerInfo = {};
    clusterLayerInfo.layerId = "clusterLayer_" + data.id + new Date().getTime();
    clusterLayerInfo.layer = "";
    return clusterLayerInfo;
  },
  //绘制图层
  renderLayer(map,data,item,imageUrl){
    // this.layerNum++;
    this.colorNum = item.sort;
    let clusterMarkers = this.createMarker(data.data,map);
    clusterMarkers.layerNum = item.sort;
    this.createCharts(clusterMarkers, data.data,imageUrl,map);
    let clusterLayer = clusterMarkers;
    clusterLayer.setVisible = this.setVisible; // 添加设置可见性函数
    clusterLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数
    clusterLayer.setZIndexOffsetHasGroup = this.setZIndexOffsetHasGroup; // 设置图层顺序函数
    clusterLayer.autoCalgraph = this.autoCalgraph; // 添加计算图例函数
    clusterLayer.name = data.name;
    clusterLayer.layerNum = item.sort;
    let zIndex = styleModify.curZindex-item.sort;//结果展示多个结果导致图层顺利不固定问题
    clusterLayer.zIndex = zIndex;
    clusterLayer.type = 'clusterLayer';

    let clusterLayerInfo = {};
    clusterLayerInfo.layerId = item.layerId;

    clusterLayerInfo.name = data.name;
    clusterLayerInfo.type = 'clusterLayer';
    clusterLayerInfo.show = data.showThumbnails !== false;
    clusterLayerInfo.html = this.calgraph(clusterLayer,clusterLayerInfo.layerId,imageUrl);
    map.overlayerInfos[item.layerId] = clusterLayerInfo;//overlayer和overlayerInfos分开存储，避免地图出错
    map.overlayers[item.layerId] = clusterLayer;

    (styleModify.layerOrderHasGroup[item.type])[clusterLayerInfo.layerId] = zIndex;
    styleModify.setLayerOrder(zIndex, clusterLayer);
    sgisLayerBase.setOverLayers(clusterLayerInfo);
  },
  /**
   * 创建专题图
   * @param {Object} map 地图实例
   * @param {Object} data 用于创建专题图的数据
   *      {
   *        "id": "", 专题图的id
   *        "name": "", 专题图的名称
   *        "datas": [
   *          {id:"",name:"",lon:"",lat:"",regioncode:"",regionname:""},{}
   *        ]
   *      }
   */

  createLayer(map, data) {
    // if (this.layerNum >= 10) {
    //   alert("聚合图叠加超过限制，请清除结果后重试");
    //   return;
    // }
    // 圆的大小 // 鼠标进入时的动态效果 // 颜色要动态改变 // 鼠标进入时的颜色
    let clusterMarkers = this.createMarker(data.data,map);
    const clusterLayer = clusterMarkers;

    this.createCharts(clusterMarkers, data.data);

    this.clusterLayer = clusterLayer;
    // this.layerNum++;
    clusterLayer.setVisible = this.setVisible; // 添加设置可见性函数
    clusterLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数
    clusterLayer.setZIndexOffset = this.setZIndexOffset; // 设置图层顺序函数
    clusterLayer.autoCalgraph = this.autoCalgraph; // 添加计算图例函数
    let clusterLayerInfo = {};
    clusterLayerInfo.layerId = "clusterLayer_" + data.id + new Date().getTime();
    styleModify.onZoomScatter(map, clusterLayer, clusterLayerInfo.layerId); // 由于聚合图在放大平移时均会改变可见性，故有此函数
    clusterLayer.layerId = clusterLayerInfo.layerId;
    clusterLayer.autoCalgraph = this.autoCalgraph;
    styleModify.layerOrder[clusterLayerInfo.layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;

    clusterLayerInfo.name = data.name;
    // clusterLayerInfo.layer = clusterLayer;

    clusterLayerInfo.type = 'cluster';
    clusterLayerInfo.show = data.showThumbnails !== false;
    clusterLayerInfo.html = this.calgraph(clusterLayer,clusterLayerInfo.layerId);
    map.overlayerInfos[item.layerId] = clusterLayerInfo;//overlayer和overlayerInfos分开存储，避免地图出错
    map.overlayers[item.layerId] = clusterLayer;

    sgisLayerBase.setOverLayers(clusterLayerInfo);
    // 为当前layer绑定设置颜色的方法
    // clusterLayer.setCustomColor = this.setCustomColor;
    return clusterLayerInfo;
  },
  createMarker(datas,map){
    const time = +new Date();
    const resultMarkers = [];
    let clusterMaker = new EchartsLayer(map);
    clusterMaker._container.className = "chart_fullscreen"
    clusterMaker._container.id = "cluster_chart_" + time;
    clusterMaker._container.style['position'] = "fixed";
    resultMarkers.push(clusterMaker);
    return resultMarkers;
  },
  createCharts(clusterLayer, datas,imageUrl,map){
    let that = this;
    let color = config.colors[this.colorNum]?config.colors[this.colorNum]:config.colors[this.colorNum%config.colors.length];
    var maxSize = 50;
    var minSize = 30;
    let datajg = (datas.maxdata - datas.mindata)/(maxSize-minSize);
    let dataTmp = [];
    for(var i = 0 ; i <  datas.polydata.length ;i ++){
      if(datas.polydata[i].value[0] !== null && datas.polydata[i].value[0] !== null){
        dataTmp.push(datas.polydata[i]);
      }
    }
    datas.polydata = dataTmp;
    let option ={};
    option = {
      color :color,
      animation: false,
      tooltip: {
        // formatter: '{b}',
        trigger: 'item',
        formatter: function(params) {
          if (params.data) {
            let data = params.data.data;
            let text = `${params.name}</br>`;
            for(let i in data){
              text += `${params.marker}${i}`+':'+`${data[i]||'-'}</br>`;
            }
            return text;
          } else {
            let text = `${params.name}</br>${params.marker}${params.value[2]}`;
            return text;
          }
        }
      },
      GLMap: {}
    };
    if(imageUrl){
      option.series=[{
        name: '聚合图',
        type: 'scatter',
        coordinateSystem: 'GLMap',
        symbol: "image://"+imageUrl,
        data: datas.polydata,
        symbolSize: function (val) {
          let size = (eval((val[2]-datas.mindata)/datajg)+minSize)||maxSize;
          return size;
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke'
        },
        hoverAnimation: true,
        label: {
          normal: {
            formatter: function(params){
              return params.data.value[2]
            },
            show: true,
            textStyle: {
                color: '#fff',
                fontSize: 9,
            },
            show: false
          }
        },
        emphasis: {
          show: true
        }
      }]
    }else{
      option.series=[{
        name: '聚合图',
        type: 'effectScatter',
        coordinateSystem: 'GLMap',
        data: datas.polydata,
        symbolSize: function (val) {
          let size = (eval((val[2]-datas.mindata)/datajg)+minSize)||maxSize;
          return size;
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke'
        },
        hoverAnimation: true,
        label: {
          normal: {
            formatter: function(params){
              return params.data.value[2]||0
            },
            show: true,
            textStyle: {
                color: '#fff',
                fontSize: 9,
            },
            show: true
          }
        },
        emphasis: {
          show: true
        }
      }]
    }
    clusterLayer[0].chart.setOption(option);
    clusterLayer[0].chart.mapbox = map;

    clusterLayer[0].chart.on('finished',function () {
      this.mapbox.clusterLayerDBclick = false;
    });

    clusterLayer[0].chart.off('dblclick');
    clusterLayer[0].chart.on('dblclick', function (param) {
        this.mapbox.off("zoomend");
        this.mapbox.clusterLayerDBclick = true;
        that.getRegion(param.data);
    });

    clusterLayer[0].chart.on('mousemove', function (param) {
      EventBus.$emit("table-actiontrigger",param.name);
      EventBus.$emit("onChart-action", param.name);
    });
    clusterLayer[0].chart.on('mouseout', function (param) {
      EventBus.$emit("table-heighLightOff",param.name);
      EventBus.$emit("offChart-action", param.name);
    });
    EventBus.$on("onChartMap", function(data){
      let microchartType = sessionStorage.getItem("microchartType");
      let selectedClusterLayer = sessionStorage.getItem("selectedClusterLayer");
      let layer = JSON.parse(selectedClusterLayer);
      if(microchartType=="clusterLayer"&&!layer.hidden){//只监听聚集图

        let index = 0;
        let polydata = datas.polydata;
        let lngLat = [];
        for(let i in polydata){
          if(polydata[i].name == data){
            index = i;
            lngLat = [polydata[i].value[0],polydata[i].value[1]]
          }
        }
        if(lngLat.length==2){
          const map = sgisMapBase.getMap();
            let bounds = map.getBounds();
            let obj = {
              area:bounds,
              lngLat:lngLat,
              inter:0
            }
            let status = mapexhance.pointContainStatus(obj);
            // 如果坐标非法的时候 status默认为true,不再飞行移动
            if(lngLat.length < 1){
              status = true;
            } else {
              if(lngLat[0] === null || lngLat[1] === null){
                status = true;
              }else if(lngLat[0] > 180 || lngLat[0]<-180){
                status = true;
              }else if(lngLat[1] > 90 || lngLat[1] < -90){
                status = true;
              }
            }
            if(!status){
              let zoom = map.getZoom();
              map.flyTo({
                center: lngLat,
                speed: 1.5,
                zoom: zoom
              })
              map.on("moveend",function(){
                clusterLayer[0].chart.dispatchAction({
                  type: "showTip",
                  seriesIndex: 0,
                  dataIndex: index
                });
              })
            }else{
              clusterLayer[0].chart.dispatchAction({
                type: "showTip",
                seriesIndex: 0,
                dataIndex: index
              });
            }
        }
      }
    });
    EventBus.$on("offChartMap", function(data){
      let microchartType = sessionStorage.getItem("microchartType");
      let selectedClusterLayer = sessionStorage.getItem("selectedClusterLayer");
      let layer = JSON.parse(selectedClusterLayer);
      if(microchartType=="clusterLayer"&&!layer.hidden){//只监听聚集图
        const map = sgisMapBase.getMap();
          clusterLayer[0].chart.dispatchAction({
            type: "hideTip",
            seriesIndex: 0,
          });
      }
    });
  },
  /* *图层样式可见性设置函数 */
  setVisible(visible) {
    styleModify.setScatterVisible(visible, this.layerId, this[0]);
  },
  /* *设置图层透明度 */
  setOpacity(opacity) {
    this[0]._container.style.opacity = opacity;
  },
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index,layerId) {
    styleModify.setZIndexOffset(index, layerId);
  },
  setZIndexOffsetHasGroup(index,layerId,chartType){
    styleModify.setZIndexOffsetHasGroup(index, layerId,chartType);
  },
  /* *图例样式计算 */
  calgraph(clusterLayer,layerId,imageUrl) {
    // let clustercolor = this.colors[clusterLayer.layerNum]!=""?this.colors[clusterLayer.layerNum]:this.colors[(this.colors.length-1)];
    let clustercolor = config.colors[this.colorNum]?config.colors[this.colorNum]:config.colors[this.colorNum%config.colors.length];
    let html = `<div class="${layerId}">`;
    if(imageUrl){
      html += `<div class='chart_item'  style='text-align:center;border-radius:60px;display:inline-block;height:45px;padding:5px;' >
        <div style = 'width:35px;height:35px;margin:0;padding:0;background:url("${imageUrl}") no-repeat;background-size: 100% 100%;'> </div>
        <p style='line-height: 3;'>${clusterLayer.name||'聚集图'}</p>
    </div>`;
    }else{
      html += `<div class='chart_item'  style='text-align:center;border-radius:60px;display:inline-block;height:45px;padding:5px;';'
     >
        <div style = 'width:35px;height:35px;margin:0;padding:0;background:${clustercolor};border:2px solid ${clustercolor};border-radius:50px;'  onMouseOver='this.style.background="radial-gradient(${clustercolor},transparent)" onMouseOut = 'this.style.background="transparent";'> </div>
        <p style='line-height: 3;'>${clusterLayer.name||'聚集图'}</p>
    </div>`;
    }
    html += '</div>';
    return html;
  },
  autoCalgraph(layerId, color) {
    const itemColor = color;
    const emphsisColor = 'red';
    const html = `
     <div class="${layerId}" style='text-align:center;padding:6px;'>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px;' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
     </div>
    `;
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
  },
  getRegion(data){
    if(data.regionCode.length == 15){//普查小区不再下钻
      return false;
    }else{
      let arr = [];
      arr.push(data);
      mapTool.clearDrawFeatures();//清除地图上的绘制
      EventBus.$emit("changeToolRegion", arr,"upOrDownDirr"); //发送区划面板
    }
  }

};
